package pl.edu.agh.mbc.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.log4j.Logger;

import pl.edu.agh.configs.ServerConfig;
import pl.edu.agh.mbc.database.dao.commons.DaoControll;
/**
 * 
 * @author wkedzior
 * 
 */
public class ServerRunner implements Runnable {

	private static final Logger LOG = Logger.getLogger( ServerRunner.class );
	private static DaoControll service;
	private static ServerConfig config;
	private ServerSocket server;
	private static ServerRunner instance = null;

	private ServerRunner() {

	}
	
	public static void init(DaoControll dataBaseService, ServerConfig config) {
		ServerRunner.service = dataBaseService;
		ServerRunner.config = config;
	}

	public synchronized static ServerRunner getInstance() {
		if (null == service || null == config)
			throw new RuntimeException("Variables are not initialized!");
		if (null == instance) {
			instance = new ServerRunner();
		}
		return instance;
	}

	public void startServer() throws Exception {
		if (null == server) {
			this.server = new ServerSocket(config.getPort());
			new Thread(this).start();
		}
	}

	private void handlerConnection() {
		try {

			Socket socket = server.accept();
			// -- uruchamiam nowy watek dla klienta
			new Thread(new ServerWorker(socket, service)).start();

		} catch (IOException e) {
			LOG.error( e);
		}
	}

	public void run() {
		LOG.debug("I listening on port " + config.getPort());
		while (true) {
			handlerConnection();
		}

	}
}
